const Router = require("koa-router");
const { Sequelize } = require("sequelize");
const { Raffle_record, Raffle } = require("@models/raffle");
const { Address } = require("@models/address");
const { Auth } = require("@middlewares/auth");
const { operatorPoint } = require("@services/operatorPoint");
const { ImgService } = require("@services/img");
const router = new Router({
  prefix: "/v1/user/raffle",
});

// 获取奖品列表
router.post("/list", new Auth().m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  where = {
    del: true,
  };
  const { count: total, rows } = await Raffle.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 我的奖品列表
router.post("/mylist", new Auth().m, async (ctx, next) => {
  const { page = 1, pageSize = 10 } = ctx.request.body;
  const offset = (page - 1) * pageSize;
  where = {
    uid: ctx.auth.uid,
  };
  const { count: total, rows } = await Raffle_record.findAndCountAll({
    where,
    limit: pageSize, // 每页数量
    offset, // 偏移量
    order: [["created_at", "desc"]], // 排序
    include: [
      {
        model: Raffle,
        where: { raffle_id: Sequelize.col("Raffle_record.raffle_id") },
        required: false,
      },
    ],
  });
  ctx.body = {
    code: 200,
    msg: "获取成功",
    total,
    data: rows,
  };
});

// 奖品详情
router.post("/detail", new Auth().m, async (ctx, next) => {
  const { raffle_id } = ctx.request.body;
  const raffle = await Raffle.findOne({
    where: { raffle_id },
  });
  if (!raffle) {
    ctx.body = {
      code: 200,
      msg: "奖品不存在",
      data: null,
    };
  } else {
    ctx.body = {
      code: 200,
      msg: "获取成功",
      data: raffle,
    };
  }
});

// 抽奖
router.post("/start", new Auth().m, async (ctx, next) => {
  // 获取用户积分

  const getPoint_count = await operatorPoint.getPoint_count(ctx.auth.uid);
  // 获取奖品列表
  const { count: total, rows } = await Raffle.findAndCountAll({
    where: { del: true },
  });
  let data = JSON.parse(JSON.stringify(rows)).filter((i) => i.stock > 0);
  if (data.length == 0) {
    throw new global.errs.AuthFailed("奖品已全部抽完,等待补充");
  }
  if (getPoint_count - data[0].point < 0) {
    throw new global.errs.AuthFailed("积分不足");
  }

  // 计算抽奖概率
  // {
  //   prize_name: '一等奖',
  //   probability: 0.01
  // },
  // {
  //   prize_name: '二等奖',
  //   probability: 0.09
  // },
  // {
  //   prize_name: '三等奖',
  //   probability: 0.9
  // },
  // {
  //   prize_name: '四等奖',
  //   probability: 40
  // },
  // {
  //   prize_name: '参与',
  //   probability: 59
  // }
  // 获取随机数 r
  // r > 0 && r <= 1 其实只有=1时才为一等奖
  // r > 1 && r <= 10 二等奖
  // r > 10 && r <= 100 三等奖
  // r > 100 && r <= 4100 四等奖
  // r > 4100 && r <= 10000 五等奖
  let getOddsSummation = (i) =>
    data.slice(0, i).reduce((s, { probability }) => s + probability * 100, 0);
  let r = Math.ceil(Math.random() * 10000);
  let raffle = data.find(
    (v, i) => r > getOddsSummation(i) && r <= getOddsSummation(i + 1)
  );

  if (!raffle) {
    await operatorPoint.consume_point(ctx.auth.uid, "抽奖消耗", rows[0].point);
    ctx.body = {
      msg: "谢谢参与",
      code: 200,
      data: {
        prize_image:
          "https://cdn.cellsplus.top/images/2024-08-29/1724940625931.png",
        prize_name: "谢谢参与",

        raffle_id: -1,
      },
    };
    return;
  }

  let { introduce, ...raffle_data } = JSON.parse(JSON.stringify(raffle));
  raffle_data.prize_image = await ImgService.getImg64(raffle_data.prize_image);
  // 创建中奖记录
  const raffle_record = await Raffle_record.create({
    uid: ctx.auth.uid,
    point: raffle_data.point,
    raffle_id: raffle.raffle_id,
    raffle_details: JSON.stringify(raffle_data),
  });

  // 更新奖品库存
  let stock = await Raffle.update(
    { stock: Sequelize.literal("stock - 1") },
    { where: { raffle_id: raffle.raffle_id } }
  );

  if (!raffle_record) {
    throw new global.errs.AuthFailed("抽奖失败");
  }

  await operatorPoint.consume_point(ctx.auth.uid, "抽奖消耗", rows[0].point);

  // 用户消耗积分
  ctx.body = {
    msg: "恭喜中奖",
    code: 200,
    total,
    data: raffle_record,
  };
});

// 兑换奖品
router.post("/update", new Auth().m, async (ctx, next) => {
  const { address_id, raffle_record_id } = ctx.request.body;

  const address_info = await Address.findOne({
    where: { address_id },
  });
  let address = JSON.stringify(address_info);

  let raffle_record = await Raffle_record.update(
    { address },
    {
      where: {
        raffle_record_id,
      },
    }
  );

  ctx.body = {
    msg: "修改成功",
    code: 200,
    data: raffle_record,
  };
});

// 中奖详情
router.post("/win/detail", new Auth().m, async (ctx, next) => {
  const { raffle_record_id } = ctx.request.body;
  const raffle = await Raffle_record.findOne({
    where: { raffle_record_id },
    include: [
      {
        model: Raffle,
        required: false,
      },
    ],
  });

  if (!raffle) {
    throw new global.errs.AuthFailed("获取失败");
  }
  ctx.body = {
    code: 200,
    msg: "获取成功",
    data: raffle,
  };
});

module.exports = router;
